const express = require('express');
const router = express.Router();
const Joi = require('joi');
const db = require('../../models');
const { authenticateToken } = require('../../middleware/auth');
const { success, error, validationError, notFound, conflict } = require('../../utils/response');

// 输入验证规则
const createTagSchema = Joi.object({
  name: Joi.string().min(1).max(30).required(),
  color: Joi.string().pattern(/^#[0-9A-Fa-f]{6}$/).optional()
});

const updateTagSchema = Joi.object({
  name: Joi.string().min(1).max(30).optional(),
  color: Joi.string().pattern(/^#[0-9A-Fa-f]{6}$/).optional()
});

/**
 * 获取标签列表
 * GET /api/tags
 */
router.get('/', authenticateToken, async (req, res) => {
  try {
    const user_id = req.user.id;
    const { keyword } = req.query;

    const where = { user_id };
    
    // 如果有关键词搜索
    if (keyword) {
      where.name = {
        [db.Sequelize.Op.like]: `%${keyword}%`
      };
    }

    const tags = await db.Tag.findAll({
      where,
      attributes: ['id', 'name', 'color', 'created_at'],
      include: [
        {
          model: db.Diary,
          as: 'diaries',
          attributes: [],
          required: false
        }
      ],
      // 添加日记数量统计
      attributes: {
        include: [
          [
            db.sequelize.fn('COUNT', db.sequelize.col('diaries.id')),
            'diary_count'
          ]
        ]
      },
      group: ['Tag.id'],
      order: [['created_at', 'ASC']]
    });

    return success(res, tags);

  } catch (err) {
    console.error('获取标签列表错误:', err);
    return error(res, '获取标签列表失败', 500);
  }
});

/**
 * 获取标签详情
 * GET /api/tags/:id
 */
router.get('/:id', authenticateToken, async (req, res) => {
  try {
    const { id } = req.params;
    const user_id = req.user.id;

    const tag = await db.Tag.findOne({
      where: { id, user_id },
      include: [
        {
          model: db.Diary,
          as: 'diaries',
          attributes: ['id', 'title', 'diary_date', 'created_at'],
          through: { attributes: [] } // 隐藏中间表字段
        }
      ]
    });

    if (!tag) {
      return notFound(res, '标签不存在');
    }

    // 对相关日记进行排序并限制数量
    if (tag.diaries && tag.diaries.length > 0) {
      tag.diaries = tag.diaries
        .sort((a, b) => new Date(b.diary_date) - new Date(a.diary_date)) // 按日期降序
        .slice(0, 10); // 限制10条
    }

    return success(res, tag);

  } catch (err) {
    console.error('获取标签详情错误:', err);
    return error(res, '获取标签详情失败', 500);
  }
});

/**
 * 创建标签
 * POST /api/tags
 */
router.post('/', authenticateToken, async (req, res) => {
  try {
    // 输入验证
    const { error: validationErr, value } = createTagSchema.validate(req.body);
    if (validationErr) {
      return validationError(res, '输入数据不合法', validationErr.details[0].message);
    }

    const user_id = req.user.id;
    const { name, color } = value;

    // 检查标签名称是否重复
    const existingTag = await db.Tag.findOne({
      where: { user_id, name }
    });

    if (existingTag) {
      return conflict(res, '标签名称已存在');
    }

    // 创建标签
    const tag = await db.Tag.create({
      user_id,
      name,
      color: color || '#87ceeb'
    });

    return success(res, tag, '标签创建成功', 200);

  } catch (err) {
    console.error('创建标签错误:', err);
    return error(res, '创建标签失败', 500);
  }
});

/**
 * 批量创建标签
 * POST /api/tags/batch
 */
router.post('/batch', authenticateToken, async (req, res) => {
  try {
    const { tags } = req.body;

    if (!Array.isArray(tags) || tags.length === 0) {
      return validationError(res, '标签数据不能为空');
    }

    if (tags.length > 20) {
      return validationError(res, '一次最多创建20个标签');
    }

    const user_id = req.user.id;
    const createdTags = [];
    const existingTags = [];

    for (const tagData of tags) {
      // 验证每个标签数据
      const { error, value } = createTagSchema.validate(tagData);
      if (error) {
        return validationError(res, `标签"${tagData.name}"数据不合法: ${error.details[0].message}`);
      }

      const { name, color } = value;

      // 检查是否已存在
      const existingTag = await db.Tag.findOne({
        where: { user_id, name }
      });

      if (existingTag) {
        existingTags.push(existingTag);
      } else {
        // 创建新标签
        const newTag = await db.Tag.create({
          user_id,
          name,
          color: color || '#87ceeb'
        });
        createdTags.push(newTag);
      }
    }

    return success(res, {
      created: createdTags,
      existing: existingTags,
      total_created: createdTags.length,
      total_existing: existingTags.length
    }, '标签批量创建完成', 200);

  } catch (err) {
    console.error('批量创建标签错误:', err);
    return error(res, '批量创建标签失败', 500);
  }
});

/**
 * 更新标签
 * PUT /api/tags/:id
 */
router.put('/:id', authenticateToken, async (req, res) => {
  try {
    const { id } = req.params;
    const user_id = req.user.id;

    // 输入验证
    const { error: validationErr, value } = updateTagSchema.validate(req.body);
    if (validationErr) {
      return validationError(res, '输入数据不合法', validationErr.details[0].message);
    }

    // 查找标签
    const tag = await db.Tag.findOne({
      where: { id, user_id }
    });

    if (!tag) {
      return notFound(res, '标签不存在');
    }

    // 如果要更新名称，检查是否重复
    if (value.name && value.name !== tag.name) {
      const existingTag = await db.Tag.findOne({
        where: { user_id, name: value.name, id: { [db.Sequelize.Op.ne]: id } }
      });

      if (existingTag) {
        return conflict(res, '标签名称已存在');
      }
    }

    // 更新标签
    await tag.update(value);

    return success(res, tag, '标签更新成功');

  } catch (err) {
    console.error('更新标签错误:', err);
    return error(res, '更新标签失败', 500);
  }
});

/**
 * 删除标签
 * DELETE /api/tags/:id
 */
router.delete('/:id', authenticateToken, async (req, res) => {
  try {
    const { id } = req.params;
    const user_id = req.user.id;

    const tag = await db.Tag.findOne({
      where: { id, user_id }
    });

    if (!tag) {
      return notFound(res, '标签不存在');
    }

    // 检查是否有关联的日记
    const diaryCount = await db.DiaryTag.count({
      where: { tag_id: id }
    });

    if (diaryCount > 0) {
      return error(res, `该标签被 ${diaryCount} 篇日记使用，无法删除`, 400);
    }

    await tag.destroy();

    return success(res, null, '标签删除成功');

  } catch (err) {
    console.error('删除标签错误:', err);
    return error(res, '删除标签失败', 500);
  }
});

/**
 * 获取热门标签
 * GET /api/tags/popular
 */
router.get('/popular/list', authenticateToken, async (req, res) => {
  try {
    const user_id = req.user.id;
    const { limit = 10 } = req.query;

    const popularTags = await db.Tag.findAll({
      where: { user_id },
      attributes: [
        'id',
        'name',
        'color',
        [db.sequelize.fn('COUNT', db.sequelize.col('diaries.id')), 'usage_count']
      ],
      include: [
        {
          model: db.Diary,
          as: 'diaries',
          attributes: [],
          required: true // 只返回有关联日记的标签
        }
      ],
      group: ['Tag.id'],
      order: [[db.sequelize.fn('COUNT', db.sequelize.col('diaries.id')), 'DESC']],
      limit: parseInt(limit)
    });

    return success(res, popularTags);

  } catch (err) {
    console.error('获取热门标签错误:', err);
    return error(res, '获取热门标签失败', 500);
  }
});

/**
 * 获取标签统计信息
 * GET /api/tags/stats
 */
router.get('/stats/summary', authenticateToken, async (req, res) => {
  try {
    const user_id = req.user.id;

    const stats = await db.Tag.findAll({
      where: { user_id },
      attributes: [
        'id',
        'name',
        'color',
        [db.sequelize.fn('COUNT', db.sequelize.col('diaries.id')), 'diary_count']
      ],
      include: [
        {
          model: db.Diary,
          as: 'diaries',
          attributes: [],
          required: false
        }
      ],
      group: ['Tag.id'],
      order: [[db.sequelize.fn('COUNT', db.sequelize.col('diaries.id')), 'DESC']]
    });

    return success(res, stats);

  } catch (err) {
    console.error('获取标签统计错误:', err);
    return error(res, '获取标签统计失败', 500);
  }
});

module.exports = router; 